package com.bytz.modules.cms.reseller.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.reseller.constant.ResellerConstant;
import com.bytz.modules.cms.reseller.entity.ResellerEndUser;
import com.bytz.modules.cms.reseller.mapper.ResellerEndUserMapper;
import com.bytz.modules.cms.reseller.service.IResellerEndUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 莱宝CMS—经销商管理—经销商/终端用户关联表 服务实现类
 * </p>
 *
 * @author KyleWang
 * @since 2022-10-10
 */
@Service
public class ResellerEndUserServiceImpl extends ServiceImpl<ResellerEndUserMapper, ResellerEndUser> implements IResellerEndUserService {

    @Override
    public List<ResellerEndUser> getByResellerId(String resellerId, String type) {
        return lambdaQuery()
                .eq(ResellerEndUser::getResellerId, resellerId)
                .eq(StringUtils.isNotBlank(type), ResellerEndUser::getType, type)
                .list();
    }

    @Override
    public Boolean deleteByResellerId(String resellerId) {
        return lambdaUpdate()
                .eq(ResellerEndUser::getResellerId, resellerId)
                .remove();
    }

    @Override
    public void updateShipToAndEndUser(Order order) {
        Set<String> resellerEndUsers = lambdaQuery().select(ResellerEndUser::getEndUserId)
                .eq(ResellerEndUser::getResellerId, order.getResellerId())
                .in(ResellerEndUser::getEndUserId, order.getShipToId(), order.getEndUserId())
                .list().stream().map(ResellerEndUser::getEndUserId).collect(Collectors.toSet());
        List<ResellerEndUser> insertList = new ArrayList<>();
        if (!resellerEndUsers.contains(order.getShipToId())) {
            ResellerEndUser insertEntity = new ResellerEndUser();
            insertEntity.setResellerId(order.getResellerId());
            insertEntity.setType(ResellerConstant.ResellerEndUserType.SHIP_TO);
            insertEntity.setEndUserId(order.getShipToId());
            insertList.add(insertEntity);
        }
        if (!resellerEndUsers.contains(order.getEndUserId())) {
            ResellerEndUser insertEntity = new ResellerEndUser();
            insertEntity.setResellerId(order.getResellerId());
            insertEntity.setType(ResellerConstant.ResellerEndUserType.SHIP_TO);
            insertEntity.setEndUserId(order.getEndUserId());
            insertList.add(insertEntity);
        }
        saveBatch(insertList);
    }
}
